<?php

namespace Beerus\Modules\DecorationTie\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\service\User as sUser;
use Doraemon\model\DesignerDecorationTieClue;
use Doraemon\model\DesignerDecorationTieClueLog;
use Doraemon\tools\ImgUrl;
use Beerus\Modules\DecorationTie\Actions\ResetStatus;

class ClueController
{
    // 列表
    public function index(Request $request,Content $content) {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $params = $request->all();

        $conditions = [
            'sign_status' => [DesignerDecorationTieClue::SIGN_STATUS_SIGNED],
            'data_status' => DesignerDecorationTieClue::STATUS_NORMAL,
        ];

        if (!empty($params['clue_id'])) {
            $conditions['clue_id'] = $params['clue_id'];
        }

        if (!empty($params['b_uid'])) {
            $conditions['b_uid'] = $params['b_uid'];
        }

        if (!empty($params['admin_name'])) {
            $uids = DesignerOperatorBind::selectByAdminName($params['admin_name']);
            $conditions['b_uid'] = $uids;
        }

        if (isset($params['sign_status'])) {
            $conditions['sign_status'] = $params['sign_status'];
        }

        //时间区间筛选
        if (!empty($params['sign_time'])) {
            //开始时间
            if(!empty($params['sign_time']['start'])) {
                $conditions['sign_time[>=]'] = $params['sign_time']['start'];
            }
            //结束时间, 最后一天
            if (!empty($params['sign_time']['end'])) {
                $conditions['sign_time[<=]'] = $params['sign_time']['end'];
            }
        }

        $total = DesignerDecorationTieClue::countByCondition($conditions);

        $conditions['LIMIT'] = [($page - 1) * $pageSize, $pageSize ];

        $list = DesignerDecorationTieClue::listByCondition($conditions);

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);

        $search_params = http_build_query($conditions);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('clue_id', '线索ID')->placeholder('请输入线索ID');
                        $filter->equal('b_uid', '商业用户UID')->placeholder('请输入设计师/装企UID');
                        $filter->equal('admin_name', '对接运营')->placeholder('请输入对接运营');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('sign_status', '签约状态')->select(DesignerDecorationTieClue::SIGN_STATUS_MAP);
                        $filter->between('sign_time', '签约时间')->date();
                    });

                    $filter->expand();
                });

                $grid->column("id", 'ID');
                $grid->column("clue_id", '线索ID')->copyable();
                // $grid->column("uid", '用户ID');
                // $grid->column("nick", '用户昵称');
                $grid->column("b_uid", '商业用户UID')->copyable();
                $grid->column("b_nick", '商业用户昵称')->display(function () {
                    $userInfo = sUser::getBasicUserInfoByCache($this->b_uid);
                    return $userInfo ? $userInfo['nick'] : '-';
                })->copyable();
                $grid->column("type", '签约类型')->display(function () {
                    return DesignerDecorationTieClue::DECORATION_TYPE_TEXT[$this->type];
                });;
                $grid->column("sign_status", '签约状态')->display(function () {
                    return DesignerDecorationTieClue::SIGN_STATUS_MAP[$this->sign_status];
                });
                $grid->column("contract_design", '设计合同')->display(function () {
                    $html = '';
                    if ($this->contract_design) {
                        foreach(explode(",", $this->contract_design) as $pic_id) {
                            $html .= "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BAUTH, $pic_id, ImgUrl::IMAGE_SIZE_SQ_THUMB)."' width=50 />";
                        }
                    }
                    return $html;
                });
                $grid->column("contract_construct", '施工合同')->display(function () {
                    $html = '';
                    if ($this->contract_construct) {
                        foreach(explode(",", $this->contract_construct) as $pic_id) {
                            $html .= "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BAUTH, $pic_id, ImgUrl::IMAGE_SIZE_SQ_THUMB)."' width=50 />";
                        }
                    }
                    return $html;
                });
                $grid->column("fee", '金额')->display(function () {
                    return "设计:{$this->design_fee}<br>施工:{$this->construction_fee}";
                });
                $grid->column("brokerage_fee", '打款金额')->display(function () {
                    return "设计:{$this->design_brokerage_fee}<br>施工:{$this->construction_brokerage_fee}";
                });
                $grid->column("brokerage_status", '打款状态')->display(function () {
                    $html = '';
                    if ($this->design_brokerage_status) {
                        $html .= "设计:<sapn class='label label-success' style='display:inline-block;'>已打款</sapn><br/>";
                    } else {
                        $html .= "设计:<sapn class='label label-danger' style='display:inline-block;'>未打款</sapn><br/>";
                    }
                    if ($this->construction_brokerage_status) {
                        $html .= "施工:<sapn class='label label-success' style='display:inline-block;'>已打款</sapn>";
                    } else {
                        $html .= "施工:<sapn class='label label-danger' style='display:inline-block;'>未打款</sapn>";
                    }
                    return $html;
                });
                $grid->column("remark", '备注');
                $grid->column("admin_name", '最后操作');
                $grid->column("admin_log", '操作记录')->modal('操作记录', function ($model) {
                    $logs = DesignerDecorationTieClueLog::listByCondition(['clue_id' => $model->clue_id]);
                    $list = [];
                    foreach($logs as $log) {
                        $info = json_decode($log['log'], true);
                        $map = [
                            'type' => '签约类型',
                            'sign_status' => '签约状态',
                            'sign_time' => '签约时间',
                            'contract_design' => '设计合同',
                            'contract_construct' => '施工合同',
                            'design_fee' => '设计费',
                            'design_brokerage_fee' => '设计佣金',
                            'design_brokerage_status' => '设计打款状态',
                            'design_brokerage_img' => '设计打款证明',
                            'construction_fee' => '施工费',
                            'construction_brokerage_fee' => '施工佣金',
                            'construction_brokerage_status' => '施工打款状态',
                            'construction_brokerage_img' => '施工打款证明',
                            'remark' => '运营备注',
                            'admin_name' => '操作人',
                        ];
                        $item = [];
                        foreach($info as $key => $value) {
                            if($map[$key]) {
                                $item[$map[$key]] = $value;
                            }
                        }
                        $list[] = [
                            '记录' => "<pre>" . rtrim(ltrim(print_r($item, true), "Array\n\("), "\n\)") . "</pre>",
                            '时间' => date("Y-m-d H:i:s", $log['add_time']),
                        ];
                    }
                    return new Table(['记录', '时间'], $list);
                });
                $grid->column("sign_time", '签约时间');
                /*
                $grid->column("edit_time", '修改时间')->display(function () {
                    return $this->edit_time ? date('Y-m-d H:i:s', $this->edit_time) : "";
                });
                 */
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();

                    if (in_array($actions->row['sign_status'], [DesignerDecorationTieClue::SIGN_STATUS_SIGNED, DesignerDecorationTieClue::SIGN_STATUS_UNSIGNED])) {
                        $actions->add(new ResetStatus);
                    }
                });
            });

        $tab = new Tab();
        $tab->add('装修搭子线索管理', $gridList->render());
        $content->row($tab);
        return $content
            ->header('装修搭子线索管理')
            ->description(' ')
            ->breadcrumb(['text' => '装修搭子线索管理']);
    }

    // 编辑
    public function edit(Content $content, $id = 0)
    {
        if($id == 0) {
            return $content
                ->header('装修搭子线索管理 - 新增')
                ->breadcrumb([
                    'text' => '装修搭子线索管理',
                    'url' => '/DecorationTie/clue/',
                ])
                ->body(self::editAction($id));
        } else {
            return $content
                ->header('装修搭子线索管理 - 编辑')
                ->breadcrumb([
                    'text' => '装修搭子线索管理',
                    'url' => '/DecorationTie/clue/',
                ])
                ->body(self::editAction($id));
        }
    }

    public function editAction($id)
    {
        if($id == 0) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = DesignerDecorationTieClue::getByCondition(['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        }

        $form_uid = $form->text('uid', '用户uid')->required()->pattern('^([1-9][0-9]*){1,10}$')->setWidth(4, 2);
        $form_buid = $form->text('b_uid', '商业用户uid')->required()->pattern('^([1-9][0-9]*){1,10}$')->setWidth(4, 2);
        $form_type = $form->select('type', '签约类型')->required()->setWidth(4, 2)->options(DesignerDecorationTieClue::DECORATION_TYPE_TEXT);
        $form_sign_time = $form->text('sign_time', '签约时间')->required()->setWidth(4, 2);
        $form_sign_status = $form->select('sign_status', '签约状态')->required()->setWidth(4, 2)->options(DesignerDecorationTieClue::SIGN_STATUS_MAP);
        if($id) {
            $form->text('clue_id', '线索id')->required()->setWidth(4, 2)->readOnly();
            $form_uid->readOnly();
            $form_buid->readOnly();
            $form_type->readOnly();
            $form_sign_time->readOnly();
            $form_sign_status->readOnly();
        }
        $form->imgUpload('contract_design', '设计合同', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BAUTH,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->setWidth(7, 2);
        $form->imgUpload('contract_construct', '施工合同', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BAUTH,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->setWidth(7, 2);
        $form->text('design_fee', '设计费用')->setWidth(4, 2)->help('需要和对应合同金额保持一致，谨慎填写');
        $form->text('design_brokerage_fee', '设计佣金')->setWidth(4, 2);
        $form->radio('design_brokerage_status', '设计佣金打款状态')->options(DesignerDecorationTieClue::DESIGN_BROKERAGE_STATUS_MAP)
            ->default(DesignerDecorationTieClue::DESIGN_BROKERAGE_STATUS_FALSE)->setWidth(4, 2)->help('需上传对应的打款证明');
        $form->imgUpload('design_brokerage_img', '设计佣金打款证明', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BAUTH,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->setWidth(7, 2);
        $form->text('construction_fee', '施工费用')->setWidth(4, 2)->help('需要和对应合同金额保持一致，谨慎填写');
        $form->text('construction_brokerage_fee', '施工佣金')->setWidth(4, 2);
        $form->radio('construction_brokerage_status', '施工佣金打款状态')->options(DesignerDecorationTieClue::CONSTRUCTION_BROKERAGE_STATUS_MAP)
            ->default(DesignerDecorationTieClue::DESIGN_BROKERAGE_STATUS_FALSE)->setWidth(4, 2)->help('需上传对应的打款证明');
        $form->imgUpload('construction_brokerage_img', '施工佣金打款证明', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BAUTH,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->setWidth(7, 2);
        $form->textarea('remark', '运营备注')->setWidth(4, 2);
        $form->action('/admin/DecorationTie/clue/save');
        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        try {
            $params = $request->all();
            if (empty($params["id"])) {
                //插入的时候判断是否为空
                // uid已存在
                $uid_white = DesignerDecorationTieClue::getByCondition([
                    'uid' => $params['uid'],
                    'b_uid' => $params['b_uid'],
                    'data_status' => DesignerDecorationTieClue::STATUS_NORMAL
                ]);
                if ($uid_white) {
                    throw new \Exception("该线索已存在，请勿重复添加");
                }
            }

            $data = [
                'uid' => $params['uid'],
                'b_uid' => $params['b_uid'],
                'clue_id' => "{$params['uid']}_{$params['b_uid']}",
                'type' => $params['type'],
                'admin_name' => Admin::user()->username,
                'contract_design' => $params['contract_design'],
                'contract_construct' => $params['contract_construct'],
                'design_fee' => $params['design_fee'],
                'design_brokerage_fee' => $params['design_brokerage_fee'],
                'design_brokerage_status' => $params['design_brokerage_status'],
                'design_brokerage_img' => $params['design_brokerage_img'],
                'construction_fee' => $params['construction_fee'],
                'construction_brokerage_fee' => $params['construction_brokerage_fee'],
                'construction_brokerage_status' => $params['construction_brokerage_status'],
                'construction_brokerage_img' => $params['construction_brokerage_img'],
                'remark' => $params['remark'],
            ];

            if (empty($params["id"])) {
                DesignerDecorationTieClue::addInfo($data);
                DesignerDecorationTieClueLog::addInfo([
                    'clue_id' => $data['clue_id'],
                    'log' => json_encode($data, JSON_UNESCAPED_UNICODE),
                ]);
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
            } else {
                DesignerDecorationTieClue::updateInfo($data, ['id' => $params['id']]);
                DesignerDecorationTieClueLog::addInfo([
                    'clue_id' => $data['clue_id'],
                    'log' => json_encode($data, JSON_UNESCAPED_UNICODE),
                ]);
                $success = new MessageBag([
                    'title' => '编辑成功'
                ]);
            }

            return redirect('/admin/DecorationTie/clue')->with(compact('success'));

        }  catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delete($id)
    {
        $update_data = [
            'data_status' => DesignerDecorationTieClue::STATUS_DELETE,
            'admin_name' => Admin::user()->username,
        ];
        //先根据id获取uid
        $tieInfo = DesignerDecorationTieClue::getByCondition(['id' => $id],"*");
        if (!DesignerDecorationTieClue::updateInfo($update_data, ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }

        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }
}
